package zzzhc.image.recognize.filter;

import zzzhc.image.recognize.Filter;
import zzzhc.image.recognize.RecognizeContext;

public class PenWidthFilter implements Filter {

	private static final long serialVersionUID = -3468789303237604707L;

	private int threshold;

	private boolean less;

	private boolean filterY;

	private boolean filterX;

	public void doFilter(RecognizeContext context) {
		if (threshold <= 0) {
			return;
		}
		if (filterY == false && filterX == false) {
			return;
		}
		if (filterY) {
			for (int y = 0; y < context.getHeight(); y++) {
				int start = -1;
				int end = -1;
				for (int x = 0; x < context.getWidth(); x++) {
					if (context.getValue(x, y) == 1) {
						if (start == -1) {
							start = x;
						}
						end = x;
					} else if (start != -1) {
						if ((less && (end - start+1) < threshold)
								|| (less == false && (end - start+1) > threshold)) {
							for (int xx = start; xx <= end; xx++) {
								context.setValue(xx, y, 0);
							}
						}
						start = -1;
						end = -1;
					}
				}
			}
		}

		if (filterX) {
			for (int x = 0; x < context.getWidth(); x++) {
				int start = -1;
				int end = -1;
				for (int y = 0; y < context.getHeight(); y++) {
					if (context.getValue(x, y) == 1) {
						if (start == -1) {
							start = y;
						}
						end = y;
					} else if (start != -1) {
						if ((less && (end - start+1) < threshold)
								|| (less == false && (end - start+1) > threshold)) {
							for (int yy = start; yy <= end; yy++) {
								context.setValue(x, yy, 0);
							}
						}
						start = -1;
						end = -1;
					}
				}
			}
		}
	}

	public boolean isFilterX() {
		return filterX;
	}

	public void setFilterX(boolean filterX) {
		this.filterX = filterX;
	}

	public boolean isFilterY() {
		return filterY;
	}

	public void setFilterY(boolean filterY) {
		this.filterY = filterY;
	}

	public boolean isLess() {
		return less;
	}

	public void setLess(boolean less) {
		this.less = less;
	}

	public int getThreshold() {
		return threshold;
	}

	public void setThreshold(int threshold) {
		this.threshold = threshold;
	}

}
